package ru.ifmo.rybakov.muclumon;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RevisionServlet extends HttpServlet {

	private static final long serialVersionUID = 8690519305085078011L;

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
//		super.doGet(req, resp);
		String idString = req.getParameter("id");
		Integer id = Integer.valueOf(idString);
		
		EntityManager em = Database.getEntityManagerFactory().createEntityManager();
		try {
			Revision revision = em.find(Revision.class, id);
			Query query = em.createQuery("SELECT e FROM Element e WHERE e.revision = :revision");
			query.setParameter("revision", revision);
			List<Element> elements = query.getResultList();
			req.setAttribute("elements", elements);
			
			query = em.createQuery("SELECT p FROM Property p");
			req.setAttribute("properties", query.getResultList());
			
			req.getRequestDispatcher("/revision/index.jsp").forward(req, resp);
		} finally {
			em.close();
		}
	}
}
